package org.wu.framework.lazy.orm.database.jpa.repository.support;

import org.wu.framework.lazy.orm.core.persistence.util.LazySQLUtil;
import org.wu.framework.lazy.orm.database.jpa.repository.query.LazyParameter;
import org.wu.framework.lazy.orm.database.jpa.repository.query.LazyQueryMetadata;
import org.wu.framework.lazy.orm.database.lambda.domain.PersistenceRepository;
import org.wu.framework.lazy.orm.database.lambda.domain.PersistenceRepositoryFactory;

import java.lang.reflect.Method;

public abstract class AbstractLazySimpleQuerySupport implements LazySimpleQuerySupport {

    private final LazyQueryMetadata lazyQueryMetadata;

    protected AbstractLazySimpleQuerySupport(LazyQueryMetadata lazyQueryMetadata) {
        this.lazyQueryMetadata = lazyQueryMetadata;
    }

    /**
     * 执行查询
     */
    @Override
    public <T> T query() {
        // 解析sql

        // 执行sql
        // 返回结果

        return doQuery();

    }

    /**
     * 执行
     *
     * @param <T>
     * @return T
     */
    protected abstract <T> T doQuery();


    /**
     * 通过 LazyQueryMetadata 构造 PersistenceRepository 对象
     * @param lazyQueryMetadata LazyQueryMetadata
     * @return PersistenceRepository
     */
    protected PersistenceRepository lazyQueryMetadata2PersistenceRepository(LazyQueryMetadata lazyQueryMetadata){

        String querySql = lazyQueryMetadata.getQuerySql();
        // sql 拼装
        for (LazyParameter parameter : lazyQueryMetadata.getParameters()) {
            querySql=querySql.replace("{"+parameter.getName()+"}", LazySQLUtil.valueToSqlValue(parameter.getValue()).toString());
        }

        // 返回数据类型
        Method queryMethod = lazyQueryMetadata.getQueryMethod();
        Class<?> returnType = queryMethod.getReturnType();
        PersistenceRepository persistenceRepository = PersistenceRepositoryFactory.create();

        persistenceRepository.setQueryString(querySql);
        persistenceRepository.setResultClass(returnType);
        persistenceRepository.setExecutionType(lazyQueryMetadata.getQueryType().getLambdaTableType());
        return persistenceRepository;

    }


}
